package server;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class SocketHandler implements Runnable {
	private Socket clientSocket;
	private ObjectInputStream ois;
	private ObjectOutputStream oos;
	
	public SocketHandler(Socket clientSocket) {
		this.clientSocket = clientSocket;
		
		try {
			oos = new ObjectOutputStream(this.clientSocket.getOutputStream());
			ois = new ObjectInputStream(this.clientSocket.getInputStream());
		}
		catch(Exception e) {
			e.printStackTrace();
		}
		
		run();
	}

	@Override
	public void run() {
		while(true) {
			try {
				Object o = ois.readObject();
				
				if(o instanceof game.Player) {
					// todo: update player stats
					//System.out.println("----------------");
					//System.out.println("Received: " + ((game.Player)o).getName());
					PlayerManager.INSTANCE.update((game.Player)o);
					System.out.println((game.Player)o);
					oos.writeObject(new game.Players(PlayerManager.INSTANCE.getPlayers()));
					oos.flush();
					oos.reset();
//					System.out.println("Sent: " + PlayerManager.getInstance().getPlayers().length + " players");
//					PlayerManager.getInstance().printPlayers();
				}	
			}
			catch(Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public void stop() { 
		try {
			ois.close();
			oos.close();
		}
		catch(Exception e) {
			e.printStackTrace();
		}
	}
}